import './style.scss'
import 'antd/dist/antd.css';
import { Component } from 'react'
import { loginAdmin } from '../../api/admin'
import withRouter from '../../util/withRouter'
import { connect } from 'react-redux'
import { setAdminInfo } from '../../store/adminSlice'
import React from 'react';
import { Button, Checkbox, Form, Input, message } from 'antd';


class Login extends Component {

  state = {
    name: '',
    pwd: ''
  };
  handleLogin = async () => {
    // 数据过滤
    if (!this.state.name) return message.info('请填写正确用户名')
    if (!this.state.pwd) return message.info('请填写正确密码')


    // 执行登录
    let res = await loginAdmin({
      name: this.state.name,
      pwd: this.state.pwd
    })
    console.log('res', res)
    console.log('props', this.props)
    this.props.dispatch(setAdminInfo(res.data))  // 全局设置adminInfo
    message.info('登录成功')
    // 重定向到 /index
    this.props.navigate('/index', { replace: true })
  }


  render() {
    return (
      <div className='fbody'>
        <Form
          className='log'
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 8,
          }}
          initialValues={{
            remember: true,
          }}

        >
          <Form.Item
            label="Username"
            name="username"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input
              value={this.state.name}
              onChange={ev => this.setState({ name: ev.target.value })}
            />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input.Password
              value={this.state.pwd}
              onChange={ev => this.setState({ pwd: ev.target.value })}
            />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{
              offset: 8,
              span: 8,
            }}
          >
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" onClick={this.handleLogin}>
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
};
const mapStateToProps = (state) => ({ ...state });
export default connect(mapStateToProps)(withRouter(Login));